#coding=utf-8
import smtplib
import sys
from email.mime.text import MIMEText
import unittest
from Config.HTMLTestRunner import HTMLTestRunner
import time,os
from email.mime.multipart import MIMEMultipart   #邮件附件类
from email.header import Header   #邮件头部模板
import configparser
from Utils.page import *
#import HTMLTestRunner

#发送带邮件的函数动作
def send_mail(file_new):
    f = open(file_new,'rb')
    mail_body = f.read()
    f.close()

    #基本信息
    smtpserver = Helper().readConfig()[0]   #163邮箱服务器
    pwd = Helper().readConfig()[1]   #163邮箱授权码
    #定义邮件主题
    msg = MIMEMultipart()
    msg['subject'] = Header(Helper().readConfig()[-1],'utf-8')
    msg['from'] = Helper().readConfig()[3]   #必须加，不加报错。发送者的邮箱
    msg['to'] = Helper().readConfig()[4]   #必须加，不加报错。接受者的邮箱

    #不加msg['from']、msg['to']报错原因，是因为发件人和收件人参数没有进行定义
    #HTML邮件正文，直接发送附件的代码片段
    body = MIMEText(mail_body,'html','utf-8')
    msg.attach(body)
    att = MIMEText(mail_body,'base64','utf-8')
    att["Content-Type"] = "application/octet-stream"
    att["Content-Disposition"] = 'attachment;filename="Interface_report.html"'
    msg.attach(att)

    #链接邮箱服务器发送邮件
    smtp = smtplib.SMTP()
    smtp.connect(smtpserver)
    print(msg["from"],pwd)
    smtp.login(msg['from'],pwd)
    smtp.sendmail(msg['from'],msg['to'],msg.as_string())
    print("邮件发送成功")

#查找最新邮件
def new_file(test_dir):
    result_dir = test_dir
    lists = os.listdir(result_dir)
    print(lists)#print(list)，列出测试报告目录下所有的文件
    lists.sort()                                        #从小到大排序文件
    file = [x for x in lists if x.endswith('.html')]    #for循环遍历以.html格式的测试报告
    file_path = os.path.join(result_dir,file[-1])       #找到测试报告目录下最新的测试报告
    return file_path                                    #返回最新的测试报告
if __name__ == '__main__':
    #print("ceshi")
    base_dir = os.path.dirname(os.path.realpath(__file__))   #获取文件当前路径
    test_dir = os.path.join(base_dir,'TestCases')            #测试用例所在路径
    test_report = os.path.join(base_dir,"Reports")           #测试报告所在路径
    testlist = unittest.defaultTestLoader.discover(test_dir,pattern='test*.py')
    now = time.strftime("%Y-%m-%d %H_%M_%S")
    filename = test_report + "\\" + now + 'result.html'
    fp = open(filename,'wb')
    runner = HTMLTestRunner(stream = fp,
                            title = u'接口自动化测试框架设计报告',
                            description = u'系统环境：Win10用例执行情况：')
    runner.run(testlist)
    fp.close()
    new_report = new_file(test_report)                       #获取最新的测试文件
    send_mail(new_report)                                    #发送最新的测试报告